package com.crm.controller.sourceController;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.crm.Business.CompareSrcVO;
import com.crm.dao.OpportunityDAO;
import com.crm.dao.PartsDAO;
import com.crm.dao.SourceCompareDAO;
import com.crm.dao.SourceInfoDAO;
import com.crm.dao.SourcesDAO;
import com.crm.dao.SupplierDAO;
import com.crm.entity.Business;
import com.crm.entity.Opportunity;
import com.crm.entity.Parts;
import com.crm.entity.SourceInfo;
import com.crm.entity.Sourcecompare;
import com.crm.entity.Sources;
import com.crm.entity.Supplier;
import com.crm.util.Constants;

@Controller
@RequestMapping("/comparesource")
public class CompareSrcController {
	protected final Log logger = LogFactory.getLog(getClass());
	@RequestMapping( "/show.do") 
	public ModelAndView insert(HttpServletRequest req,HttpSession session, ModelAndView model) throws Exception{
		Business bus=(Business)session.getAttribute("business");
		if(bus==null)return new ModelAndView("/jsp/index.jsp");
		
			//OpportunityDAO oprD=new OpportunityDAO();
			
			List<Opportunity> opr=null;
			try{
				opr=(List<Opportunity>)OpportunityDAO.getSingleInstance().getAllEnqCompares(bus.getBusinessId());
					logger.info("opportunity list is "+opr);
			}catch(NullPointerException e){
				e.printStackTrace();
			}
			
			  model = new ModelAndView("/jsp/CompareSources.jsp");
				model.addObject("opprtunity",opr);
				model.addObject("submenu", "sourcingInfo");
				model.addObject("menuName","sourcingInfo");
				 
		 
				return model;
	}

		@RequestMapping( "/scompare.do") 
		public ModelAndView sourceCompare(HttpServletRequest req,HttpSession session, ModelAndView model) 
		throws Exception{

			Business bus=(Business)session.getAttribute("business");
			if(bus==null)return new ModelAndView("/jsp/index.jsp");

			String ref=req.getParameter("refno");
			logger.info("refno is "+ref);
				//OpportunityDAO oprD=new OpportunityDAO();

					List<Opportunity> opr=(List<Opportunity>)OpportunityDAO.getSingleInstance().getallenqs(bus.getBusinessId());
						logger.info("opportunity list is "+opr);
						

						List<CompareSrcVO> listscompare=new ArrayList<CompareSrcVO>();
						Opportunity o=OpportunityDAO.getSingleInstance().getByRefNo(bus.getBusinessId(),ref);
						int rfnum=o.getId();
						SourceInfoDAO siDAO=new SourceInfoDAO();
						List<SourceInfo> srcInfo=siDAO.getSrcDetails(rfnum,bus.getBusinessId());
						System.out.println("the sourceInfo list is  "+srcInfo);
						if(srcInfo!=null){
						Iterator<SourceInfo> itr=srcInfo.iterator();
						int k=0;
						while(itr.hasNext()){
							Object ob=itr.next();
							SourceInfo si=(SourceInfo)ob;
							System.out.println(si);
							int pr=si.getPrtnum();
							System.out.println("The partno is "+pr);
							int req_qty=si.getReq_qty();
							int srid=si.getSourceid();
							int splid=si.getSuplierid();
							logger.info(splid);
							float uprice=si.getUtprice();
							String soCurrency=si.getCurrency();
							String ofrPart=si.getOfferPartNo();
							//for comparision of lower price...
							int availQty=si.getQty_available();
							int moq=si.getMoq();
							
							int spq=si.getStdpackqty();
							String cond=si.getConditions();
							PartsDAO pDAO=new PartsDAO();
							Parts prt=pDAO.findById(pr,bus.getBusinessId(),rfnum);	
							String prtNum=prt.getPrtnum();
			
							String desc=prt.getDescription();
							SourcesDAO sDAO=new SourcesDAO();
							System.out.println("Source Id Is:"+srid);
							Sources sd=sDAO.findById(srid,bus.getBusinessId());
							
							String srcName=sd.getSourceName();
							String splName="";
							SupplierDAO supDAO=new SupplierDAO();
							if(splid!=0){
								
							Supplier spl=supDAO.findById(splid,bus.getBusinessId());	
							splName=spl.getName();
							logger.info(splName);
							}
								k++;
								CompareSrcVO csrc=new CompareSrcVO(false,k,prtNum,desc,ofrPart,req_qty,srcName,splName,uprice,soCurrency,availQty,moq,cond,spq,si.getPrtnum());
								listscompare.add(csrc);
							
						
						}
						}
						/*SupplierDAO suppD=new SupplierDAO();
						List<Supplier> suplist=(List<Supplier>)suppD.findAll();*/
				  model = new ModelAndView("/jsp/CompareSourcesRes.jsp");
					model.addObject("lscompare",listscompare);
					model.addObject("clientdet",o.getOrganisation());
					model.addObject("division",o.getDivision());
					model.addObject("user",o.getUser());
					return model;
		}
		
		
		@RequestMapping( "/autocompare.do") 
		public ModelAndView autoCompare(HttpServletRequest req,HttpSession session, ModelAndView model)
		throws Exception{

			Business bus=(Business)session.getAttribute("business");

			if(bus==null)return new ModelAndView("/jsp/index.jsp");

			String ref=req.getParameter("refno");
			logger.info("refno is "+ref);
				//OpportunityDAO oprD=new OpportunityDAO();
					
						
						List<CompareSrcVO> listscompare=new ArrayList<CompareSrcVO>();
						Opportunity o=OpportunityDAO.getSingleInstance().getByRefNo(bus.getBusinessId(),ref);
						int rfnum=o.getId();
						SourceInfoDAO siDAO=new SourceInfoDAO();
						List<SourceInfo> srcInfo=siDAO.getSrcDetails(rfnum,bus.getBusinessId());
						if(srcInfo!=null){
						Iterator<SourceInfo> itr=srcInfo.iterator();
						String partNumb="";
						float unitpr=0;
						while(itr.hasNext()==true){
							Object ob=itr.next();
							SourceInfo si=(SourceInfo)ob;
							int pr=si.getPrtnum();
							int req_qty=si.getReq_qty();
							//int srid=si.getSourceid();
							int splid=si.getSuplierid();
							logger.info(splid);
							float uprice=si.getUtprice();
							int availQty=si.getQty_available();
							int moq=si.getMoq();
							
							int spq=si.getStdpackqty();
							PartsDAO pDAO=new PartsDAO();
							Parts prt=pDAO.findById(pr,bus.getBusinessId(),rfnum);	
							String prtNum=prt.getPrtnum();
							if(prtNum.length()==0){
								prtNum=prt.getDescription();
							}
							//SourcesDAO sDAO=new SourcesDAO();
							
							//Sources sd=sDAO.findById(srid,bus.getBusinessId());
							
							String splName="";
							SupplierDAO supDAO=new SupplierDAO();
							if(splid!=0){
								
							Supplier spl=supDAO.findById(splid,bus.getBusinessId());
								
							splName=spl.getName();
							logger.info(splName);
							}
							if(!partNumb.equals(prtNum)){
								logger.info("hello we are in if part;");
								partNumb=prtNum;
								unitpr=uprice;
								}
							else{  logger.info("hello we are in else;");
								
							if(unitpr>uprice && ((moq==req_qty && req_qty==availQty)|| (spq==1 && moq<=req_qty))){
										
										unitpr=uprice;
										
										
										
									}
								}
							
						
						}
						
						
						}
						
						model = new ModelAndView("/jsp/CompareSourcesRes.jsp");
						model.addObject("lscompare",listscompare);
					
						model.addObject("submenu", "sourcingInfo");
						model.addObject("menuName","admin");
				 
						return model;
	  
		
}
		@RequestMapping( "/exportsave.do") 
		public ModelAndView exportsave(HttpServletRequest req,HttpSession session, ModelAndView model)
		throws Exception{
			Business bus=(Business)session.getAttribute("business");
			if(bus==null)return new ModelAndView("/jsp/index.jsp");
			String  rowcount=req.getParameter("columnCount");
			String  refnum=req.getParameter("reflist");
			int rcount=0;
			if(rowcount!=null)
			{
		 rcount=Integer.parseInt(rowcount);
			}
		//OpportunityDAO oprDAO=new OpportunityDAO();
		Opportunity o=OpportunityDAO.getSingleInstance().getByRefNo(bus.getBusinessId(),refnum);
		int rfnum=o.getId();
		SourceCompareDAO scDAO=new SourceCompareDAO();
		//deleting previous records for this enquiery.
	scDAO.deletelast(rfnum,bus.getBusinessId());
	List<Sourcecompare> lsc=new ArrayList<Sourcecompare>();
		for(int i=0;i<rcount;i++){
			String check=req.getParameter("autocheck"+i);
			logger.info("the auto check value is "+req.getParameter("autocheck"+i));
			if(check!=null){
				String prtName=req.getParameter("partno"+i);
				String prtId=req.getParameter("partid"+i);
				String desc=req.getParameter("desc"+i);
				if(prtName==null&&desc==null)
					continue;
				String source=req.getParameter("source"+i);
				String offPartNO=req.getParameter("offpartno"+i);
				logger.info("the source name is"+source);
				String splName=req.getParameter("supplier"+i);
				logger.info("the supplier name is"+splName);
				String uprice=req.getParameter("uprice"+i);
				
					Sourcecompare sc=new Sourcecompare();
					float unitval=0;
				 unitval=Float.parseFloat(uprice);
							SourcesDAO srDAO=new SourcesDAO();
							SupplierDAO supDAO=new SupplierDAO();
							int sno = 0;
							int partid=Integer.parseInt(prtId);
								sno = srDAO.getByName(source,bus.getBusinessId()).getId();
							
							int splNum=0;
							if(splName!=null&&splName.trim().length()>0){
								splNum=supDAO.getByName(splName,bus.getBusinessId()).getId();
								
							}
							sc.setBusinessId(bus);
							sc.setEnqnum(rfnum);
							sc.setPrtnum(partid);
							sc.setSrcnum(sno);
							sc.setSupplier(splNum);
							sc.setUnitprice(unitval);
							sc.setOfferingPartNo(offPartNO);
							lsc.add(sc);
							
						}
			
						
					}
		scDAO.insertList(lsc);
		//updating opportunity for further processing
		String st=Constants.ST_SOURCES_COMPARED;
		OpportunityDAO.getSingleInstance().updateStatus(bus.getBusinessId(),st,rfnum);
			
				
		 model = new ModelAndView("redirect:/newquot/show.do");
		 
		 model.addObject("msgsrc", "Sucessfully Compared Selected Enquiery Number is "+refnum+" Continue With Quotation ");
		 model.addObject("submenu", "sourcingInfo");
		 model.addObject("currentref",refnum);
			model.addObject("menuName","sourcingInfo");
		return model;
		}
}




						
